package net.toocruel.iqismart.entity.config;

import net.toocruel.iqismart.entity.rbac.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/7 下午2:12
 */
@Configuration
public class UserIDAuditorBeanConfig implements AuditorAware<Long> {

    @Override
    public Long getCurrentAuditor() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            return null;
        }
        if (ctx.getAuthentication() == null) {
            return null;
        }
        if (ctx.getAuthentication().getPrincipal() == null) {
            return null;
        }
        Object principal = ctx.getAuthentication().getPrincipal();
        if (principal.getClass().isAssignableFrom(User.class)) {
            return ((User) principal).getId();
        } else {
            return null;
        }
    }
}
